#ifndef EVENTLOOP
#define EVENTLOOP

#include "Common.h"
#include "Poller.h"
// #include "TimeWheel.h"
#include <mutex>
#include <thread>
#include <memory>
#include <poll.h>
#include <sys/eventfd.h>
#include <functional>

// 事件处理和监控
// 线程安全问题：把一个链接的操作都放在同一个线程内
// 如何保证上一行可以实现
// 解决方法：添加一个任务队列，
class TimeWheel;
constexpr uint64_t task_size = 1024;

class EventLoop
{
    using func = std::function<void()>;

private:
    void RunAllTask();
    void WakeUpEventFd();
    void ReadEventFd();
    static int CreateEventFd();

public:
    EventLoop();
    void Start();
    void RunInLoop(const func &);
    void QueueInLoop(const func &);
    void UpdateEvent(Channel *channel);
    void RemoveEvent(Channel *channel);
    bool IsInLoop();
    void AssertInLoop();
    void TimerAdd(uint64_t id, uint32_t delay, const func &);
    void TimerRefersh(uint64_t id);
    void TimerCancel(uint64_t id);
    bool HasTimer(uint64_t id);
    ~EventLoop();

private:
    int _event_fd;
    Poller _poller;
    std::unique_ptr<TimeWheel> _time_wheel;
    std::unique_ptr<Channel> _event_channel;
    std::mutex _mutex; // 保证线程安全
    std::thread::id _thread_id;
    std::vector<func> _task_queue;
};

#endif